package com.yuanfeng.commoms.aspect;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @ClassName CacheHttpServletRequestFilter
 * @Description 1
 * @Author hyq
 * @Date 2023/6/14 19:38
 * @Version 1.0
 **/

@Component
public class CacheHttpServletRequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String contentType = httpServletRequest.getContentType();

        //判断请求类型
        if (contentType == null) { //表单请求
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else if (contentType.startsWith("multipart/")) { //文件上传类型
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else if (contentType.startsWith("application/json")) {//json请求

            ServletRequest requestWrapper = null;
            if (servletRequest instanceof HttpServletRequest) {
                requestWrapper = new JsonRequestWrapper(httpServletRequest);
            }
            //获取请求中的流如何，将取出来的字符串，再次转换成流，然后把它放入到新request对象中。
            // 在chain.doFiler方法中传递新的request对象
            if (requestWrapper != null) {
                filterChain.doFilter(requestWrapper, servletResponse);
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
            return;
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

    }
    @Override
    public void destroy() {
    }
}